<script setup name="OssConfig" lang="ts">
import { DeleteOutlined, FormOutlined } from '@ant-design/icons-vue'
import {
  addOssConfig,
  changeOssConfigStatus,
  delOssConfig,
  getOssConfig,
  listOssConfig,
  updateOssConfig,
} from '@/api/system/ossConfig'
import type { OssConfigForm, OssConfigQuery, OssConfigVO } from '@/api/system/ossConfig/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'))
const router = useRouter()
const ossConfigList = ref<OssConfigVO[]>([])
const buttonLoading = ref(false)
const loading = ref(true)
const ids = ref<Array<number | string>>([])
const total = ref(0)
const message = useMessage()
const modal = useModal()
const queryFormRef = ref()
const ossConfigFormRef = ref()

const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})

// 列显隐信息
const columns = ref<FieldOption[]>([
  { key: 0, label: `主建`, visible: true },
  { key: 1, label: `配置key`, visible: false },
  { key: 2, label: `访问站点`, visible: true },
  { key: 3, label: `自定义域名`, visible: true },
  { key: 4, label: `桶名称`, visible: true },
  { key: 5, label: `前缀`, visible: true },
  { key: 6, label: `域`, visible: true },
  { key: 7, label: `桶权限类型`, visible: true },
  { key: 8, label: `状态`, visible: true },
])

const initFormData: OssConfigForm = {
  ossConfigId: undefined,
  configKey: '',
  accessKey: '',
  secretKey: '',
  bucketName: '',
  prefix: '',
  endpoint: '',
  domain: '',
  isHttps: 'N',
  accessPolicy: '1',
  region: '',
  status: '1',
  remark: '',
}
const data = reactive<PageData<OssConfigForm, OssConfigQuery>>({
  form: { ...initFormData },
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configKey: '',
    bucketName: '',
    status: '',
  },
  rules: {
    configKey: [{ required: true, message: 'configKey不能为空', trigger: 'blur' }],
    accessKey: [
      { required: true, message: 'accessKey不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 200,
        message: 'accessKey长度必须介于 2 和 100 之间',
        trigger: 'blur',
      },
    ],
    secretKey: [
      { required: true, message: 'secretKey不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 100,
        message: 'secretKey长度必须介于 2 和 100 之间',
        trigger: 'blur',
      },
    ],
    bucketName: [
      { required: true, message: 'bucketName不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 100,
        message: 'bucketName长度必须介于 2 和 100 之间',
        trigger: 'blur',
      },
    ],
    endpoint: [
      { required: true, message: 'endpoint不能为空', trigger: 'blur' },
      {
        min: 2,
        max: 100,
        message: 'endpoint名称长度必须介于 2 和 100 之间',
        trigger: 'blur',
      },
    ],
    accessPolicy: [{ required: true, message: 'accessPolicy不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询对象存储配置列表 */
async function getList() {
  loading.value = true
  const res = await listOssConfig(queryParams.value)
  ossConfigList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 取消按钮 */
function cancel() {
  dialog.visible = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  ossConfigFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialog.visible = true
  dialog.title = '添加对象存储配置'
}

/** 修改按钮操作 */
async function handleUpdate(row?: OssConfigVO) {
  reset()
  const ossConfigId = row?.ossConfigId || ids.value[0]
  const res = await getOssConfig(ossConfigId)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改对象存储配置'
}

/** 提交按钮 */
function submitForm() {
  ossConfigFormRef.value?.validate().then(async () => {
    buttonLoading.value = true
    if (form.value.ossConfigId)
      await updateOssConfig(form.value).finally(() => buttonLoading.value = false)
    else
      await addOssConfig(form.value).finally(() => buttonLoading.value = false)

    message.success('新增成功')
    dialog.visible = false
    await getList()
  })
}

/** 状态修改  */
async function handleStatusChange(row: OssConfigVO) {
  const text = row.status === '0' ? '启用' : '停用'
  modal.confirm({
    title: `确认要"${text}""${row.configKey}"配置吗?`,
    onOk: async () => {
      await changeOssConfigStatus(row.ossConfigId, row.status, row.configKey)
      await getList()
      message.success(`${text}成功`)
    },
    onCancel: () => {
      row.status = row.status === '0' ? '1' : '0'
    },
  })
}

/** 删除按钮操作 */
async function handleDelete(row?: OssConfigVO) {
  const ossConfigIds = row?.ossConfigId || ids.value
  modal.confirm({
    title: `是否确认删除OSS配置编号为"${ossConfigIds}"的数据项?`,
    onOk: async () => {
      loading.value = true
      await delOssConfig(ossConfigIds).finally(() => loading.value = false)
      await getList()
      message.success('删除成功')
    },
  })
}

/** 返回按钮操作 */
function handleClose() {
  router.back()
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex-between">
        <div>
          <a-form ref="queryFormRef" :model="queryParams" layout="inline" :label-col="{ style: 'width:68px' }" label-width="68px">
            <a-form-item label="配置key" prop="configKey">
              <a-input
                v-model:value="queryParams.configKey" placeholder="配置key" allow-clear style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="桶名称" prop="bucketName">
              <a-input
                v-model:value="queryParams.bucketName" placeholder="请输入桶名称" allow-clear style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="是否默认" prop="status">
              <a-select v-model="queryParams.status" placeholder="请选择状态" allow-clear style="width: 200px">
                <a-select-option key="0" label="是" value="0">
                  是
                </a-select-option>
                <a-select-option key="1" label="否" value="1">
                  否
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-space>
                <a-button type="primary" @click="handleQuery">
                  搜索
                </a-button>
                <a-button @click="resetQuery">
                  重置
                </a-button>
              </a-space>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col>
              <a-button v-hasPermi="['system:oss:add']" type="primary" @click="handleAdd">
                新增
              </a-button>
            </a-col>
            <a-col>
              <a-button @click="handleClose()">
                关闭
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card shadow="hover">
      <template #title />

      <a-table :loading="loading" :pagination="false" :data-source="ossConfigList">
        <a-table-column v-if="columns[0].visible" title="主建" align="center" data-index="ossConfigId" />
        <a-table-column v-if="columns[1].visible" title="配置key" align="center" data-index="configKey" />
        <a-table-column v-if="columns[2].visible" title="访问站点" align="center" data-index="endpoint" width="200" />
        <a-table-column v-if="columns[3].visible" title="自定义域名" align="center" data-index="domain" width="200" />
        <a-table-column v-if="columns[4].visible" title="桶名称" align="center" data-index="bucketName" />
        <a-table-column v-if="columns[5].visible" title="前缀" align="center" data-index="prefix" />
        <a-table-column v-if="columns[6].visible" title="域" align="center" data-index="region" />
        <a-table-column v-if="columns[7].visible" title="桶权限类型" align="center" data-index="accessPolicy">
          <template #default="{ record }">
            <a-tag v-if="record.accessPolicy === '0'" type="warning">
              private
            </a-tag>
            <a-tag v-if="record.accessPolicy === '1'" type="success">
              public
            </a-tag>
            <a-tag v-if="record.accessPolicy === '2'" type="info">
              custom
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column v-if="columns[8].visible" title="是否默认" align="center" prop="status">
          <template #default="{ record }">
            <a-switch
              v-model:checked="record.status" checked-value="0" un-checked-value="1"
              @change="handleStatusChange(record)"
            />
          </template>
        </a-table-column>
        <a-table-column title="操作" fixed="right" align="center" width="150" class-name="small-padding">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button
                v-hasPermi="['system:oss:edit']" type="link"
                @click="handleUpdate(record)"
              >
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button
                v-hasPermi="['system:oss:remove']" type="link"
                @click="handleDelete(record)"
              >
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-5">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>
    <!-- 添加或修改对象存储配置对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="800px" append-to-body>
      <a-form ref="ossConfigFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:120px' }" label-width="120px">
        <a-form-item label="配置key" prop="configKey">
          <a-input v-model:value="form.configKey" placeholder="请输入配置key" />
        </a-form-item>
        <a-form-item label="访问站点" prop="endpoint">
          <a-input v-model:value="form.endpoint" placeholder="请输入访问站点" />
        </a-form-item>
        <a-form-item label="自定义域名" prop="domain">
          <a-input v-model:value="form.domain" placeholder="请输入自定义域名" />
        </a-form-item>
        <a-form-item label="accessKey" prop="accessKey">
          <a-input v-model:value="form.accessKey" placeholder="请输入accessKey" />
        </a-form-item>
        <a-form-item label="secretKey" prop="secretKey">
          <a-input v-model:value="form.secretKey" placeholder="请输入秘钥" show-password />
        </a-form-item>
        <a-form-item label="桶名称" prop="bucketName">
          <a-input v-model:value="form.bucketName" placeholder="请输入桶名称" />
        </a-form-item>
        <a-form-item label="前缀" prop="prefix">
          <a-input v-model:value="form.prefix" placeholder="请输入前缀" />
        </a-form-item>
        <a-form-item label="是否HTTPS">
          <a-radio-group v-model:value="form.isHttps">
            <a-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value" :label="dict.value">
              {{ dict.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="桶权限类型">
          <a-radio-group v-model:value="form.accessPolicy">
            <a-radio value="0">
              private
            </a-radio>
            <a-radio value="1">
              public
            </a-radio>
            <a-radio value="2">
              custom
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="域" prop="region">
          <a-input v-model:value="form.region" placeholder="请输入域" />
        </a-form-item>
        <a-form-item label="备注" prop="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button :loading="buttonLoading" type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
